// Copyright (C) 2025 woodycpp
//
// This work is licensed under the Creative Commons Attribution-ShareAlike 4.0
// International License. To view a copy of this license, visit
// https://creativecommons.org/licenses/by-sa/4.0/
//
// You are free to:
//   * Share — copy and redistribute the material in any medium or format
//   * Adapt — remix, transform, and build upon the material
//
// Under the following terms:
//   * Attribution — You must give appropriate credit, provide a link to the
//   license,
//     and indicate if changes were made. You may do so in any reasonable
//     manner, but not in any way that suggests the licensor endorses you or
//     your use.
//   * ShareAlike — If you remix, transform, or build upon the material, you
//   must
//     distribute your contributions under the same license as the original.
//
// In short: You must credit the original author (woodycpp, 2025) and share any
// derivative works under the same CC-BY-SA-4.0 license.

#pragma once

#include <stdlib.h>

typedef struct LNode {
    int data;
    struct LNode *link;
} LNode, *LinkList;

// 尾插法创建带头结点的单链表，使用数组a中n个元素初始化结点，返回头指针
LinkList CreateList(int a[], int n) {
    LinkList head = (LinkList)malloc(sizeof(LNode));  // 创建头结点
    if (!head) {
        return NULL;  // 内存分配失败，返回空指针
    }
    head->link = NULL;  // 链表初始为空表
    LinkList end = head;  // 尾指针指向最后一个结点，用于插入新结点
    for (int i = 0; i < n; ++i) {
        LinkList node = (LinkList)malloc(sizeof(LNode));  // 创建新链表结点
        if (!node) {
            return NULL;  // 内存分配失败，返回空指针
        }
        node->data = a[i];  // 将数组a中的元素赋值给新结点的数据域
        end->link = node;  // 将新结点插入到尾结点之后
        end = node;        // 更新尾指针指向新结点
    }
    end->link = NULL;  // 尾结点的指针域置空，此句不可省
    return head;
}